/**
 * 
 */
package org.tiger.netty.client.handler;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author liuwenlai
 */
public class TigerNettyClient {

	private String host;

	private final int port;

	public TigerNettyClient() {
		this.port = 8089;
		this.host = "127.0.0.1";
	}

	public TigerNettyClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void start() throws Exception {
		EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

		try{
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
					.remoteAddress(new InetSocketAddress(host, port))
					.handler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel sc) throws Exception {
							sc.pipeline().addLast(new TigerClientHandler());
						}
					});
			ChannelFuture channelFuture = bootstrap.connect().sync();
			channelFuture.channel().closeFuture().sync();
		} catch (Exception e){

		} finally{
			eventLoopGroup.shutdownGracefully().sync();
		}
	}

	public static void main(String[] args) throws Exception {

		if (args.length == 0){
			new TigerNettyClient().start();
		} else{
			TigerNettyClient client = new TigerNettyClient(args[0],
					Integer.valueOf(args[1]));
			client.start();
		}
	}

}
